import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Notify } from 'vant'

//当前请求数
let reqNum = 0

export default function $axios(options) {
  options.method = options.method || 'GET'
  options.data = options.data || {}
  options.params = options.params || {}
  //如果存在token 就放在authorization请求头中
  if (store.state.token) {
    options.headers = {
      'authorization': store.state.token
    }
  }

  //200ms后还没有加载完 并且当前请求数为0时 就开启加载界面 (reqNum-1 是因为异步 最少reqNum就为1)
  setTimeout(() => {
    if (reqNum-1 === 0) {
      store.commit('setIsLoading', true)
    }
  }, 200)

  //当前请求数+1
  reqNum++

  return axios(options)
  .then(
    res => {
      //保存token
      if (res.headers['authorization']) {
        store.commit('setToken', res.headers['authorization'])
      }
      if (res.data.reLogin) {
        store.commit('loginOut')
        router.push('/login')
      }
      
      return res.data
    },
    err => {
      Notify('数据请求失败!')
      throw err
    }
  )
  .finally(
    () => {
      //当前请求数-1
      if (reqNum > 0) reqNum--

      if ( reqNum === 0) {
        //当前请求数为0时 关闭加载界面
        store.commit('setIsLoading', false)
      }
    }
  )
}